package com.cnswhy.cloud.server.iot.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.DecimalFormat;

/**
 * @author HuangHL
 * @date 2015/12/10
 * @see
 */
@Slf4j
public class FileUtil
{
    
    /**
     * 日志
     */
    
    /**
     * 私有化构造函数
     */
    private FileUtil()
    {
        
    }
    
    /*public static File zipImageFile(File srcfile) {
        try {
            BufferedImage im = ImageIO.read(srcfile);
            *//* 原始图像的宽度和高度 *//*
            int width = im.getWidth();  
            int height = im.getHeight();  
            
            float resizeTimes = 0.5f;
            
            *//* 调整后的图片的宽度和高度 *//*
            int toWidth = (int) (width * resizeTimes);
            int toHeight = (int) (height * resizeTimes);
            
            *//** 宽,高设定 *//*
            BufferedImage tag = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(  
                    im.getScaledInstance(toWidth, toHeight,  
                            java.awt.Image.SCALE_SMOOTH), 0, 0, null); 
            
            String os = System.getProperty("os.name");
            String tmpdir = null;
            File tempFile = new File(System.getProperty("java.io.tmpdir"));
            File jpgFile = File.createTempFile("temp", ".jpg", tempFile);
            *//** 压缩之后临时存放位置 *//*
            //FileOutputStream out = new FileOutputStream(jpgFile.getAbsolutePath());
            //JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            //JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
            *//** 压缩质量 *//*
            //jep.setQuality(0.9f, true);
            //encoder.encode(tag, jep);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(tag, "jpg", jpgFile.getAbsolutePath());

            out.flush();
            b = out.toByteArray();
            out.close();
            return jpgFile;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }*/
    
    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static String getClassPathFilePath()
    {
        String url = FileUtil.class.getClassLoader().getResource("").toString();
        url = url.replaceAll("file:", "");
        if (url.contains(":") && url.startsWith("/"))
        {
            // windows平台的路径，去到前面的“/”
            url = url.substring(1, url.length());
        }
        return url;
    }
    
    public static String getFileSize(long fileS)
    {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024)
        {
            fileSizeString = df.format((double) fileS) + "B";
        }
        else if (fileS < 1048576)
        {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        }
        else if (fileS < 1073741824)
        {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        }
        else
        {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }
    
    /**
     * 描述：NIO文件写入
     * 作者：张进飞
     * 时间：2016年7月22日 下午7:30:58
     * @param file
     * @param currentDirPath
     * @param fileName
     * @throws IOException
     */
    @SuppressWarnings("resource")
    public static void writeFileNIO(File file, String currentDirPath, String fileName) throws IOException
    {
        File afterDir = new File(currentDirPath);
        if (!afterDir.isDirectory())
        {
            afterDir.mkdir();
        }
        File afterfile = new File(currentDirPath + File.separator + fileName);
        if (afterfile.isFile())
        {
            afterfile.delete();
        }
        FileChannel in = null;
        FileChannel out = null;
        try
        {
            in = new FileInputStream(file).getChannel();
            out = new FileOutputStream(afterfile).getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (in.read(buffer) != -1)
            {
                buffer.flip();
                out.write(buffer);
                buffer.clear();
            }
        }
        catch (Exception e)
        {
            log.error("<== NOI读写，异常", e);
        }
        finally
        {
            if (null != in)
            {
                in.close();
            }
            if (null != out)
            {
                out.close();
            }
        }
    }
    
    /**
     * 上传文件 到web
     * 
     * @param file
     * @param currentFilePath
     * @throws IOException
     */
    public static void writeFile(InputStream in, String currentDirPath, String fileName) throws IOException
    {
        // 这是你要保存之后的文件，是自定义的，本身不存在
        File afterDir = new File(currentDirPath);
        if (!afterDir.isDirectory())
        {
            afterDir.mkdir();
        }
        File afterfile = new File(currentDirPath + "/" + fileName);
        if (afterfile.isFile())
        {
            afterfile.delete();
        }
        
        // 定义文件输出流，用来把信息写入afterfile文件中
        FileOutputStream fos = new FileOutputStream(afterfile);
        // 文件缓存区
        byte[] b = new byte[1024];
        // 将文件流信息读取文件缓存区，如果读取结果不为-1就代表文件没有读取完毕，反之已经读取完毕
        while (in.read(b) != -1)
        {
            // 将缓存区中的内容写到afterfile文件中
            fos.write(b);
            fos.flush();
            
        }
        if (fos != null)
        {
            fos.close();
        }
        if (in != null)
        {
            in.close();
        }
    }
    
    /**
     * 上传文件 到web
     * 
     * @param file
     * @param currentFilePath
     * @throws IOException
     */
    public static void writeFile(File file, String currentDirPath, String fileName) throws IOException
    {
        // 这是你要保存之后的文件，是自定义的，本身不存在
        /* File afterDir = new File(currentDirPath);
        if (!afterDir.isDirectory())
        {
            afterDir.mkdir();
        }
        File afterfile = new File(currentDirPath + "/" + fileName);
        if (afterfile.isFile())
        {
            afterfile.delete();
        }
        
        // 定义文件输出流，用来把信息写入afterfile文件中
        FileOutputStream fos = new FileOutputStream(afterfile);
        // 文件缓存区
        byte[] b = new byte[1024];*/
        // 将文件流信息读取文件缓存区，如果读取结果不为-1就代表文件没有读取完毕，反之已经读取完毕
        /* while (in.read(b) != -1)
        {
            // 将缓存区中的内容写到afterfile文件中
            fos.write(b);
            fos.flush();
        
        }
        if(fos != null){
            fos.close();
        }
        if(in != null){
            in.close();
        }*/
    }
    
    /**
     * @Description: 读取指定文件的内容
     * @param filePath 文件目录
     * @return String
     * @throws
     */
    public static String readFile(String filePath)
    {
        String fileContent = "";
        BufferedReader bufferedReader = null;
        try
        {
            //          bufferedReader = new BufferedReader(new FileReader(filePath));
            bufferedReader = new BufferedReader(new InputStreamReader(FileUtil.class.getResourceAsStream(filePath)));
            String str;
            while ((str = bufferedReader.readLine()) != null)
            {
                fileContent += str;
            }
            
        }
        catch (Exception e)
        {
            log.error("文件" + filePath + "读取失败:" + e.getMessage());
        }
        finally
        {
            if (bufferedReader != null)
            {
                try
                {
                    bufferedReader.close();
                }
                catch (IOException e)
                {
                    log.error("文件流" + filePath + "关闭失败:" + e.getMessage());
                }
            }
        }
        return fileContent;
    }
    
    /**
     * 字节数组转换为文件
     * 
     * @author lixiao
     * @date 2018/04/18
     * @param buffer
     * @param filePath
     */
    public static void bytesToFile(byte[] buffer, final String filePath)
    {
        File file = new File(filePath);
        OutputStream output = null;
        BufferedOutputStream bufferedOutput = null;
        try
        {
            output = new FileOutputStream(file);
            bufferedOutput = new BufferedOutputStream(output);
            bufferedOutput.write(buffer);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (null != bufferedOutput)
            {
                try
                {
                    bufferedOutput.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if (null != output)
            {
                try
                {
                    output.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
    
    /**
     * 描述：获取xml配置文件
     * 作者：张进飞
     * 时间：2016年6月21日 上午9:28:01
     * @param objName
     * @param filePath
     * @return
     */
    /*public static Iterator<?> findXMLForAll(String objName,String filePath){
        Iterator<?> iterator = null;
        String realPath = FileUtil.class.getClassLoader().getResource("config").getPath()+filePath;
        SAXReader reader = new SAXReader();
        File file = new File(realPath);
        try
         {
           Document document = reader.read(file);
           Element root = document.getRootElement();// 得到根节点
           iterator = root.elementIterator(objName);
        }
        catch (DocumentException e)
        {
            log.error("获取xml配置文件 , 异常" , e);
        }
        return iterator;
    }*/
    
}
